<template>
	<page>
	<view class='notice'>
	    <image class='noticeIcon' src='/static/images/chat/notice.png'></image>
	    <view class='noticeContent'>
	        <view class="example">
	        <view class="marquee_box">
	            <view class="marquee_text" :style="orientation+':'+marqueeDistance+'px;font-size:'+size+'px;'">
	            {{notice}}
	            </view>
	        </view>
	        </view>
	    </view>
	    <image class='noticeIcon' src='/static/images/chat/list.png' @tap='About'></image>
	</view>
		<image v-if="speak" class='speakGif' src='/static/images/chat/speak.gif'></image>
	
	<scroll-view :scroll-y="true" id="recordWrapper" :scroll-top="scrollTop" :scroll-with-animation="false" class='chat-msg-box' :upper-threshold="50" @scrolltoupper="pushHistory"> 
	
	
	
	
	
	<view  v-for="(item,index) in messageArr" :key="idx">
	    <view class='enter' v-if="item.type=='enter'">
	        <view class='enterMsg'>欢迎{{item.nick}}进入</view>
	    </view>
	    
	   
	    <!--文本消息-->
	    <view class='chat-msg' v-if="item.type=='text'&&!item.isMe">
	        <image class='user-avatar' :src="item.avatar" @tap="gotoUserDetail" :data-item="item"></image>
	        <view class='msg'>
	            <view class='user-name'>{{item.nick}}</view>
	            <view class='msg-box'>
	               <rich-text :nodes="item.nodes" class='content'>{{item.text}}</rich-text>
	            </view>
	        </view>
	    </view>
	    <view class='chat-msg-my' v-if="item.type=='text'&&item.isMe">
	        <image class='user-avatar-my' :src="item.avatar" @tap="gotoUserDetail" :data-item="item"></image>
	        <view class='msg-my'>    
	            <view class='msg-box-my' >
	                <rich-text :nodes="item.nodes" class='content-my' >{{item.text}}</rich-text>
	              
	            </view>
	        </view>
	    </view>
	
	    <!--图片消息-->
	    <view class='chat-msg' v-if="item.type=='image'&&!item.isMe">
	        <image class='user-avatar' :src="item.avatar" @tap="gotoUserDetail" :data-item="item"></image>
	        <view class='msg'>
	            <view class='user-name'>{{item.nick}}</view>
	            <view class='msg-box' @tap='rangImg' :data-src="item.nodes[0].attrs.src">
	                <rich-text :nodes="item.nodes" class='content-img' @longtap='showMsgMenu' :data-index="index">{{item.text}}</rich-text>
	                 <view class="menu-list" v-if="selectMenuIndex == index" >
	                <view class="menu-item" :data-msg="item.text" :data-index="index" @tap="deleteMsg">撤回</view>
	                <view class="menu-item">回复</view>
	                 <view class="menu-item" @tap="closeMenu">关闭</view>
	                </view>
	            </view>
	        </view>
	    </view>
	
	    <view class='chat-msg-my' v-if="item.type=='image'&&item.isMe">
	        <image class='user-avatar-my' :src="item.avatar" @tap="gotoUserDetail" :data-item="item"></image>
	        <view class='msg-my'>
	            <view class='msg-box-my' @tap='rangImg' :data-img="item.nodes[0].attrs.src">
	                <rich-text :nodes="item.nodes" class='content-my-img'>{{item.text}}</rich-text>
	            </view>
	        </view>
	    </view>
	
	    <!--位置-->
	    <view class='chat-msg' v-if="item.type=='geo' && !item.isMe">
	        <image class='user-avatar' :src="item.avatar" @tap="gotoUserDetail" :data-item="item"></image>
	        <view class='msg'>
	            <view class='user-name'>{{item.nick}}</view>
	            <view class='msg-box'>
	                <map class='content' :longitude="item.lng" :latitude="item.lat" :markers="item.markers" scale="14"></map>
	            </view>
	        </view>
	    </view>
	
	    <view class='chat-msg-my' v-if="item.type=='geo' && item.isMe">
	        <image class='user-avatar-my' :src="item.avatar" @tap="gotoUserDetail" :data-item="item"></image>
	        <view class='msg-my'>
	            <view class='user-name-my'></view>
	            <view class='msg-box-my'>
	                <map class='content-my' :longitude="item.lng" :latitude="item.lat" :markers="item.markers" scale="14">
	
	                </map>
	            </view>
	        </view>
	    </view>
	    <!--语音-->
	    <view class='chat-msg' v-if="item.type=='audio' && !item.isMe">
	        <image class='user-avatar' :src="item.avatar" @tap="gotoUserDetail" :data-item="item"></image>
	        <view class='msg'>
	            <view class='user-name'>{{item.nick}}</view>
	            <view class='msg-box'>
	                <view class='content' :data-audio="item.file.url" @tap='play' @longpress='audioToText'>
	                     {{item.file.audioText}}
	                    <view :class="item.file.timeLen<5?'voice-shot':item.file.timeLen<10?'voice-middle':'voice-long'">
	                       <image class='voice-img' src='/static/images/chat/other-voice.png'></image> {{item.file.timeLen}}
	                    </view>
	                </view>
	            </view>
	        </view>
	    </view>
	
	    <view class='chat-msg-my' v-if="item.type=='audio' && item.isMe">
	        <image class='user-avatar-my' :src="item.avatar" @tap="gotoUserDetail" :data-item="item"></image>
	        <view class='msg-my'>
	            <view class='msg-box-my'>
	                <view class='content-my' :data-audio="item.file.url" @tap='play' @longpress='audioToText'>
	                    {{item.file.audioText}}
	                    <view :class="item.file.timeLen<5?'voice-shot':item.file.timeLen<10?'voice-middle':'voice-long'">
	                    {{item.file.timeLen}}<image class='voice-img' :src="normalPic"></image>
	                    </view>
	                </view>
	            </view>
	        </view>
	    </view>
	
	</view>
	</scroll-view>
	
	<view class='bottom-box'>
	    <view class='input-box'>
	        <image v-if="!show" @tap="isShow" class='keyborad' src='/static/images/chat/keyborad.png'></image>
	        <image v-if="show" @tap="isShow" class='keyborad' src='/static/images/chat/speak.png'></image>
	        <view  v-if="!show" @longpress="speakStart"  @touchend="speakEnd" class='speak dp-flex-xy-center'>按住  说话</view>
	        <input  v-if="show"  :focus="focusFlag" :value="content" cursor-spacing='1' @input='content' class='inputs'  placeholder="说点什么" confirm-type='send' ></input>
	      
	        <image class='keyborad' catchtap='toggleEmoji' src='/static/images/chat/emoji.png'></image>
	        <image  v-if="!show"  class='keyborad' src='/static/images/chat/add.png' @tap='animate'></image>
	        <view v-if="show" class="send" @tap='sendTextMsg'>发送</view>
	    </view>
	    <view class='else' v-if="animate">
	        <view class='choose-box' catchtap='chooseImg'>
	            <view class='container'>
	                <image class='box-img' src='/static/images/chat/photo.png'></image>
	            </view>
	            <text class='txts'>相册</text>
	        </view>
	        <view class='choose-box' @tap="noMore">
	            <view class='container'>
	                <image class='box-img' src='/static/images/packet.jpg'></image>
	            </view>
	            <text class='txts'>红包</text>
	        </view>
	         <button class='choose-box-call' open-type='contact'>
	            <view class='container-call'>
	                <image class='box-img-call' src='/static/images/chat/call.png'></image>
	            </view>
	            <text class='txts'>呼叫总部</text>
	        </button>
	         <button class='choose-box' @tap="banAll" open-type='share'>
	            <view class='container'>
	                <image class='box-img' src='/static/images/share_fff.jpg'></image>
	            </view>
	            <text class='txts'>邀请好友</text>
	        </button>
	    </view>
	    <view v-if="emojiFlag" class='emoji'>
	        <component-emoji bind:EmojiClick="emojiCLick" bind:EmojiSend="sendTextMsg"></component-emoji>
	    </view>
	</view>
	
	</page>
</template>

<script>
	var NIM = require('@/vendor/NIM_Web_NIM_weixin_v5.9.1.js')
	var iconBase64Map = require('@/utils/imageBase64.js')
	var Chatroom = require('@/vendor/NIM_Web_Chatroom_weixin_v5.9.1.js')
	var formatTime = require('@/utils/gyzjModel.js').formatTime
	var generateRichTextNode = require('@/utils/gyzjModel.js').generateRichTextNode
	var generateImageNode = require('@/utils/gyzjModel.js').generateImageNode
	var generateFingerGuessImageFile = require('@/utils/gyzjModel.js').generateFingerGuessImageFile
	import app from '@/App.vue';
	import {GYZJMODEL as gyzjModel}from '@/utils/gyzjModel.js';
	export default {
		data() {
			return {
				roomid: '',
				address: '',
				chatMsg: "",
				animate: false,
				show: false,
				content: '',
				messageArr: [], // 渲染的数据
				onlineMember: [], // 在线成员 [{account,avatar,nick,type}]
				accountMap: {}, // 存储了账号map，目的是账号去重
				moreId: '', //详情id
				scrollTop: 0,
				messageWrapperMaxHeight: null, // 消息列表容器最大高度
				myId: '',
				notice: '',
				emojiFlag: false, //emoji键盘标志位
				lat: '',
				lng: '',
				markers: '',
				speak: false, //语音gif显示控制
				speakFilePath: '', //语音文件临时存储
				timeLen: '',
				limit: 20,
				reverseTime: 0,
				audioText: '',
				text: '51淘甄貨,一个可以省钱的购物平台',
				marqueePace: 1,//滚动速度
				marqueeDistance: 0,//初始滚动距离
				size: 14,
				orientation: 'left',//滚动方向
				playGif:'/static/images/chat/speak.gif',
				normalPic:'/static/images/chat/my-voice.png',
				interval: 20, // 时间间隔
			}
		},
		onLoad:function(options){
			console.log('options的值开始',options);
			let self = this;
			let roomid = options.roomId;
			let address = ['https://' + options.roomAddress];
			let token = app.globalData.prevtoken;
			let account = app.globalData.userInfo.accid;
			let roomName = options.roomName;
			let appKey = "7d169e7365827a4e517f19bc1f9d4d3e";
			this.moreId= options.id;
			this.myId= app.globalData.userInfo.accid;
			this.roomid= roomid;
			this.address= address;
			/**
			 * 当进入聊天室存在聊天室实例，则先退出，再重连
			 */
			if (app.globalData.chatroomInstance) {
			  // debugger;
			  console.log("退出聊天室a");
			  app.globalData.chatroomInstance.disconnect();
			  app.globalData.chatroomInstance = null;
			  this.initIM(appKey, account, token);
			} else {
			  console.log('连接服务器a');
			  this.initIM(appKey, account, token);
			};
			/**
			 * count会为0，需要初始化成功后再赋值
			 */
			let count = this.onlineMember.length
			// 设置顶部标题
			uni.setNavigationBarTitle({
			  // title: '长沙.' + roomName + '(' + count + ')',
			  // title: '长沙.' + roomName,
			  title: roomName,
			});
			console.log('获取公告的开始a');
			//获取公告内容
			gyzjModel.prototype.getChatMore(options.id).then(res => {
				console.log('公告res开始的值',res);
				console.log('获取公告的开始',res.data.announcement);
			  this.notice= res.data.announcement == null || res.data.announcement == '' ? '暂无公告' : res.data.announcement;
			  let that = this;
			  let length = that.text.length * that.size;//文字长度
			  let windowWidth = uni.getSystemInfoSync().windowWidth;// 屏幕宽度
			  that.length= length;
			  that.windowWidth= windowWidth;
			  that.runMarquee();// 水平一行字滚动完了再按照原来的方向滚动
			});
		},
		methods: {
			//公告跑马灯
			runMarquee: function () {
			  let that = this;
			  let interval = setInterval(function () {
				//文字一直移动到末端
				if (-that.marqueeDistance < that.length+2000) {
				  that.marqueeDistance= that.marqueeDistance - that.marqueePace;
				} else {
				  clearInterval(interval);
				  that.marqueeDistance= that.windowWidth;
				  that.runMarquee();
				}
			  }, that.interval);
			},
			/*网易云的初始化*/
			initIM: function(appKey, account, token) {
			    if (app.globalData.nim) {
			      this.initChatRoom();
			    } else {
			      //初始化
			      var nim = NIM.getInstance({
			        appKey: appKey,
			        account: account,
			        token: token,
			        onconnect: this.onConnect,
			        onwillreconnect: this.onWillReconnect,
			        ondisconnect: this.onDisconnect,
			        // 同步完成
			        onsyncdone: this.onSyncDone
			      });
			      // 暂存聊天室实例
			      app.globalData.nim = nim;
			      this.getHistory(true);
			      this.getMemberList(this.roomid);
			      this.scrollToBottom()
			    };
			  },
			  /*如果有直接执行记录*/
			  initChatRoom: function() {
				  let self = this;
				  let roomid = self.roomid;
				  let address = self.address;
				  let token = app.globalData.prevtoken;
				  let account = app.globalData.userInfo.accid;
				  // 获取指定聊天室实例
				  let chatroomInstance = Chatroom.getInstance({
					appKey: "c366812544b1d978c223249f7c22f911",
					account: account,
					token: token,
					reconnectionAttempts: 10,
					chatroomId: roomid,
					chatroomAddresses: address,
					onconnect: self.onChatroomConnect,
					onerror: self.onChatroomError,
					onwillreconnect: self.onChatroomWillReconnect,
					ondisconnect: self.onChatroomDisconnect,
					onmsgs: self.onChatroomMsgs
				  });
			  //debugger;
			  // 暂存聊天室实例
			  app.globalData.chatroomInstance = chatroomInstance;
			},
			/*直接得到历史记录的操作*/
			getHistory(isFirst = false) {
			    console.log('4');
			    console.log('to:' + this.roomid);
			    console.log('limit:' + this.limit);
			    console.log('endTime:' + this.reverseTime);
			    let self = this;
			    this.limit=this.limit;
			
				app.globalData.nim.getHistoryMsgs({
				  scene: 'team',
				  to: this.roomid,
				  limit: this.limit,
				  endTime: this.reverseTime,
				  asc: true,
				  reverse: true,
				  msgTypes: ['text', 'image', 'audio'],
				  done: function (err, msg) {
					console.log('錯誤1:' + err);
					console.log('消息1:' + msg);
					if (!msg.msgs || err) {
					  // console.log('我的地');
					  // console.log(allMsg + '---' + myId);
					  console.log(msg.msgs);
					  return;
					}
			
					let allMsg = msg.msgs.filter(item => item != 'custom')
					let arr = [];
					let myId = self.data.myId;
			
					for (let i = 0; i < allMsg.length; i++) {
					  if (0 == i) {
						self.reverseTime= allMsg[i].time;
					  }
					  // if (allMsg[i].type != 'custom') {
					  let isMe = myId == allMsg[i].from
					  // 添加到渲染队列
					  let msgType = allMsg[i].type
					  let displayTimeHeader = formatTime(allMsg[i].time)
					  let list = {
						detail: allMsg[i],
						account: allMsg[i].from,
						nick: allMsg[i].fromNick,
						text: allMsg[i].text,
						file: allMsg[i].file, // image消息才有此字段
						type: allMsg[i].type, // "image"
						time: allMsg[i].time,
						displayTimeHeader,
						isMe: isMe,
						msgId: allMsg[i].idServer,
						avatar: '',
						nodes: msgType == 'text' ? generateRichTextNode(allMsg[i].text) : generateImageNode(allMsg[i].file)
					  }
					  arr.unshift(list)
			
					}
					for (let i = 0; i < arr.length; i++) {
			
					  if (isFirst == false) {
						console.log('数据1');
						self.dealHistroyAvatar(arr[i], false, arr.length)
					  } else {
						console.log('数据2');
						self.dealHistroyAvatar(arr[i], true, arr.length)
					  }
					};
					uni.hideLoading();
				  }
				})
			},
			/*获取群组成员列表*/
		  getMemberList(roomid) {
			console.log('roomid' + roomid);
			let self = this;
			app.globalData.nim.getTeamMembers({
			  roomid: roomid,
			  done: (error, obj) => {
				if (error) {
				  return;
				}
				self.members= obj.members;
			  }
			})
		  },
			/**
		     * 滚动页面到底部
		     */
		    scrollToBottom() {
		      let self = this
		      wx.createSelectorQuery().select('#recordWrapper').boundingClientRect(function(rect) {
		        if (rect && rect.bottom > self.messageWrapperMaxHeight) {
		          self.scrollTop=999999;
		        }
		      }).exec();
		    },
			onChatroomMsgs(msgs) {
			    //console.log(msgs)
			    let self = this
			    let msg = msgs
			    switch (msg.type) {
			      // case 'notification':
			      //     {
			      //         self.addNotificationToRender(msg)
			      //         break
			      //     }
			      case 'text':
			        {
			          self.getAvatar(msg, false) //传入处理头像     
			          break
			        }
			      case 'image':
			        {
			          self.getAvatar(msg, false)
			          break
			        }
			      case 'custom':
			        {
			          self.addCustomMsgToRender(msg)
			          break
			        }
			      case 'tip':
			        {
			          self.addTipMsgToRender(msg)
			          break
			        }
			      case 'audio':
			        {
			          self.getAvatar(msg, false)
			          break
			        }
			      case 'robot':
			        {
			
			        }
			      default:
			        {
			          //  self.addOtherMsgToRender(msg)
			          break
			        }
			    }
			    // 滚动到底部
			    self.scrollToBottom()
			  },
			/**
			   * 发送消息
			   */
			  sendCustomMsg: function(content, successCallBack) {
			    app.globalData.chatroomInstance.sendCustomMsg({
			      content: content,
			      done: (err, msg) => {
			        if (err) {
			          //console.log(err)
			          return
			        }
			        // 刷新界面
			        this.addCustomMsgToRender(msg)
			      }
			    })
			    //console.log(content, 'ppppp')
			  },
			/**
			   * 添加自定义消息到渲染队列中
			   */
			  addCustomMsgToRender(msg) {
			
			    // 添加到渲染队列
			    let displayTimeHeader = formatTime(msg.time)
			    // let customContent = JSON.parse(msg['content'])
			    let renderType = msg.content
			
			    this.messageArr= [...this.messageArr, {
			        account: msg.from,
			        nick: msg.fromNick,
			        text: msg.text,
			        content: msg.content, // 自定义消息才有此字段
			        type: renderType, // "custom"、猜拳
			        time: msg.time,
			        displayTimeHeader,
			      }]
			    //console.log(msg, 'custom')
			  },
			//获取用户当前位置
			  getLocation() {
			    let that = this
			    uni.getLocation({
			      type: 'wgs84',
			      success(res) {
			        const latitude = res.latitude
			        const longitude = res.longitude
			        that.setData({
			          lat: latitude,
			          lng: longitude
			        })
			        that.sendLocation(that.lat, that.lng)
			      }
			    })
			  },
			sendLocation(lat, lng) {
			    let self = this
			    app.globalData.chatroomInstance.sendGeo({
			      scene: 'p2p',
			      to: 'account',
			      geo: {
			        lng: lng,
			        lat: lat,
			        title: 'local'
			      },
			      done: (err, msg) => {
			        if (err) {
			          //console.log(err)
			          return
			        }
			        // 刷新界面
			        self.addOtherMsgToRender(msg)
			        // 滚动到底部
			        self.scrollToBottom()
			      }
			    })
			  },
			/**
			   * 添加其他类型消息到渲染队列
			   */
			  addOtherMsgToRender(msg) {
			    // 添加到渲染队列
			    let markers = {
			      id: 999999,
			      name: "选择位置",
			      iconPath: "/images/loc.png",
			      latitude: msg.geo.lat,
			      longitude: msg.geo.lng,
			      width: 44,
			      height: 44,
			    }
			    let geos = []
			    geos.push(markers)
			    //console.log(msg, 'local')
			    let isMe = this.data.myId == msg.from
			    let displayTimeHeader = formatTime(msg.time)
			    this.content= '';
			    this.messageArr= [...this.data.messageArr, {
			        account: msg.from,
			        nick: msg.fromNick || '',
			        text: msg.text,
			        type: msg.type,
			        time: msg.time,
			        isMe: isMe,
			        avatar: msg.fromAvatar,
			        displayTimeHeader,
			        lat: msg.geo.lat,
			        lng: msg.geo.lng,
			        markers: geos,
			        nodes: [{
			          type: 'geo',
			          text: `暂不支持该类型消息,请到手机或电脑客户端查看！`
			        }]
			      }]
			  },
			  /*功能暂未开放*/
			noMore() {
			    uni.showToast({
			      title: '该功能尚未开发,敬请期待',
			      icon: 'none',
			      duration: 2000,
			    })
			  },
			  //开始录音
			speakStart() {
			  this.speak= true;
		  
			  const options = {
				duration: 100000, //指定录音的时长，单位 ms
				sampleRate: 16000, //采样率
				numberOfChannels: 1, //录音通道数
				encodeBitRate: 96000, //编码码率
				format: 'mp3', //音频格式，有效值 aac/mp3
				frameSize: 50, //指定帧大小，单位 KB
			  }
			  //开始录音
		   
			  recorderManager.start(options);
			  recorderManager.onStart(() => {});
			  //错误回调
			  recorderManager.onError((res) => {
				//console.log(res, '错误回调');
			  })
			},
			//停止录音
			  speakEnd() {
			    this.speak= false;
			    recorderManager.stop();
			    recorderManager.onStop((res) => {
			      console.log('停止录音')
			      this.speakFilePath= res.tempFilePath;
			      this.timeLen= parseInt(res.duration / 1000);
			      this.sendSpeakFileToNOS(res.tempFilePath)
			    })
			  },
			 //播放声音
			  play(e) {
			     innerAudioContext.autoplay = true
			     innerAudioContext.src = e.currentTarget.dataset.audio
			     innerAudioContext.onPlay(() => {
			       //console.log('开始播放')
			     })
			     innerAudioContext.onError((res) => {
			       // console.log('发生错误' + error);
			       //console.log(res.errMsg)
			       //console.log(res.errCode)
			     })
			     innerAudioContext.onStop(()=>{
			       console.log('播放完成')
			     })
			   },
			//语音识别
			  audioToText(e, url, datas) {
			
			    let self = this
			    app.globalData.nim.audioToText({
			      url: url,
			      done: function(err, msg) {
			        uni.hideLoading()
			        if (err) {
			          console.log(err, 'err')
			          return
			        }
			        console.log('语音转文字', msg);
			        datas.file['timeLen'] = self.timeLen;
			        datas.file['audioText'] = msg.text;
			
			        console.log(datas, 'aaa');
			
			        self.addAudioToRender(datas)
			        //滚动到底部
			        self.scrollToBottom()
			      }
			    });
			  },
			//其他人语音识别
			  audioToTextOther(e, url, datas) {
			    let self = this
			    app.globalData.nim.audioToText({
			      url: url,
			      done: function(err, msg) {
			        uni.hideLoading()
			        if (err) {
			          //console.log(err, 'err')
			          return
			        }
			        //console.log('语音转文字', msg);
			        datas.file['timeLen'] = parseInt(datas.file.dur / 1000);
			        datas.file['audioText'] = msg.text;
			
			        //console.log(datas, 'other');
			
			        self.addAudioToRender(datas)
			        //滚动到底部
			        self.scrollToBottom()
			      }
			    });
			  },
			
			 /*发送语音*/
			  sendSpeakFileToNOS(res) {
			    uni.showLoading({
			      title: '发送中...',
			    })
			    let self = this
			    let tempFilePaths = res
			    // 上传文件到nos
			    app.globalData.chatroomInstance.sendFile({
			      type: 'audio',
			      wxFilePath: tempFilePaths,
			      done: function(err, msg) {
			        uni.hideLoading()
			        if (err) {
			          //console.log(err, 'err')
			          return
			        }
			        // 刷新界面
			        self.audioToText(res, msg.file.url, msg)
			      }
			    })
			  },
			 
			/*添加语音消息到渲染队列中*/
			  addAudioToRender(msg) {
			    let isMe = this.myId == msg.from;
			    //console.log(msg, isMe, 'speak')
			    // 添加到渲染队列
			    let displayTimeHeader = formatTime(msg.time)
			    this.conten= '';
			    this.animate= false;
			    this.messageArr= [...this.data.messageArr, {
			        account: msg.from,
			        nick: msg.fromNick,
			        text: msg.text,
			        file: msg.file, // image消息才有此字段
			        type: msg.type, // "image"
			        time: msg.time,
			        displayTimeHeader,
			        isMe: isMe,
			        timeLen: msg.timeLen,
			        audioText: msg.audioText,
			        avatar: msg.fromAvatar,
			        nodes: generateImageNode(msg.file)
			      }]
			   
			    //console.log(this.data.messageArr, 'ppppp')
			  },
			
			/*添加历史消息到渲染队列中*/
			  addMsg(msg) {
			    let msgList = [...msg, ...this.messageArr]
			    let newArr = this.unique(msgList);
			    this.conten= '';
			    this.animate= false;
			    this.messageArr= newArr;
			  },
			  //历史消息去重
			    unique(arr) {　　
			      var res = [arr[0]];　　
			      for (var i = 1; i < arr.length; i++) {　　　　
			        var repeat = false;　　　　
			        for (var j = 0; j < res.length; j++) {　　　　　　
			          if (arr[i].displayTimeHeader == res[j].displayTimeHeader) {　　　　　　　　
			            repeat = true;　　　　　　　　
			            break;　　　　　　
			          }　　　　
			        }　　　　
			        if (!repeat) {　　　　　　
			          res.push(arr[i]);　　　　
			        }　　
			      }　　
			      return res;
			    },
			 // 进入联系我们
			    handleContactUsTap: function () {
			         uni.navigateTo({
			             url: '../../../user-center/contact-us/contact-us',
			         })
			     },
			   //用户点击头像获取信息
			     gotoUserDetail(e) {
			       console.log(e);
			       var id = e.currentTarget.dataset.item.account;
			       var arr = id.split('gy');
			       id = arr[1];
			       uni.navigateTo({
			         // url: '/pages/worker-spacing/worker-spacing?account=' + e.currentTarget.dataset.item.from,
			         url: '../../../user-center/my-info/cardcase/cardcase?id=' + id,
			       })
			     },
			   //自己加的方法
			    bindMsgBoxClick() {
			      this.emojiFlag= false;
			      this.animate= false;
			    },
				/*历史记录的操作*/
				dealHistroyAvatar(msgs, isFirst = false, pushLength) {
				    console.log('歷史消息');
				    let dataMsg = msgs;
				    let self = this;
				    let list = this.data.messageArr;
				    let linList = this.data.linList;
				    // let arr = [];
				    app.globalData.nim.getUser({
				      account: dataMsg.account,
				      done: (err, msg) => {
				        if (err) {
				          return;
				        }
				        dataMsg.avatar = msg.avatar;
				        dataMsg['from'] = msg.account;
				        dataMsg['history'] = true;
				        linList.unshift(dataMsg);
				        if (linList.length % pushLength == 0 && linList.length > 0) {
				          uni.hideLoading()
				          linList.sort(function (item1, item2) {
				            return item1.time - item2.time
				          })
				          console.log(linList.concat(list));
				          self.messageArr= linList.concat(list);
				          self.linList= [];
						  if (isFirst) {
						    self.scrollToBottom();
						  } else {
						    self.scrollToCenter();
						  }
				          setTimeout(function () {
				            self.loadMoreStatus= false;
				          }, 100)
				        } else {
				          self.linList= linList;
				        }
				      }
				    })
				  },
				  /*追加历史记录*/
			  pushHistory() {
			      console.log('3');
			      let _this = this;
			      if (this.loadMoreStatus == false) {
			        this.loadMoreStatus= true;
			        uni.showLoading({
			          title: "加载中"
			        })
			        _this.contentHeigth();
			        _this.getHistory();
			      }
			    },
				
				
				
				
				
				
				
				
				
			 /**
			   * 即将重连
			   */
			  onChatroomWillReconnect(obj) {
				console.log('重新连接的操作');
			  },
			  /**
			   * 已经断开连接
			   */
			  onChatroomDisconnect(error) {
				console.log('已经断开连接');
			  },
			  /**
			 * 发生错误
			 */
			onChatroomError(error, obj) {
			  //console.log('onerror', error, obj);
			  this.toastAndBack()
			},
			/**
			   * 提示错误信息并返回
			   */
			  toastAndBack() {
			    clearTimeout(this.pageTimer)
			    this.pageTimer = setTimeout(() => {
			      uni.showToast({
			        title: '连接已断开,即将返回',
			        duration: 2000,
			        success: function() {
			          uni.redirectTo({
			            url: '/pages/chat-room/chat-room',
			          })
			        }
			      })
			    }, 200)
			  },
			 /**
			 * 连接上服务器,有动作建议在同步完成后再做
			 */
			//   onConnect() {
			//     //console.log('连接成功');
			// },
			onChatroomConnect(chatroomInfo) {
			  var self = this;
			  // console.log('连接上服务器', chatroomInfo);
			  //this.getChatroomMembers();
			  this.sendCustomMsg('enter');
			},
		}
	}
</script>

<style>
	/* pages/chat-room/chat-room-detail/chat-room-detail.wxss */
	
	.notice {
	  width: 100%;
	  height: 80upx;
	  background: rgb(244, 244, 244);
	  position: fixed;
	  top: 0;
	  display: flex;
	  justify-content: space-around;
	  align-items: center;
	  z-index: 9;
	}
	
	.noticeIcon {
	  width: 40upx;
	  height: 40upx;
	}
	
	.noticeContent {
	  width: 80%;
	  height: 60upx;
	  border-right: 10upx;
	  background: white;
	  padding-left: 10upx;
	  display: flex;
	  align-items: center;
	  color: #5f6062;
	  font-size: 30upx;
	  overflow: hidden;
	  border-radius: 8upx;
	}
	
	::-webkit-scrollbar {
	  width: 0;
	  height: 0;
	  color: transparent;
	}
	
	.chat-msg-box {
	  width: 94%;
	  margin: 0 3%;
	  margin-top: 80upx;
	  padding-bottom: 70upx;
	}
	
	.chat-msg {
	  width: 100%;
	  display: flex;
	  margin-top: 20upx;
	}
	
	.user-avatar {
	  width: 93upx;
	  height: 80upx;
	  border-radius: 10upx;
	}
	
	.msg {
	  /* width: 75%; *//* margin-left: 10upx; */
	  width: 100%;
	  margin-left: 10upx;
	  display: block;
	  overflow: hidden;
	}
	
	.user-name {
	  width: 100%;
	  height: 40upx;
	  font-size: 30upx;
	  color: gray;
	}
	
	.msg-box {
	  display: flex;
	}
	
	.thin {
	  width: 20upx;
	  height: 20upx;
	}
	
	.content {
	  min-width: 10%;
	  max-width: 95%;
	  margin-top: 10upx;
	  background: white;
	  border-radius: 10upx;
	  padding: 10upx 20upx 10upx 20upx;
	  font-size: 30upx;
	}
	
	.content-img {
	  min-width: 10%;
	  max-width: 95%;
	  margin-top: 10upx;
	  background: rgb(153, 152, 152);
	  border-radius: 10upx;
	  padding: 10upx 20upx 10upx 20upx;
	  font-size: 30upx;
	}
	
	.keyborad {
	  width: 80upx;
	  height: 80upx;
	  /* margin-top: 10upx; */
	}
	
	.speak {
	  width: 50%;
	  height: 80upx;
	  /* border: 1px solid #339900; */
	  border: 1px solid #bfc0c2;
	  border-radius: 20upx;
	  color: #bfc0c2;
	  /* margin-top: 10upx; */
	  padding: 0 20upx;
	  line-height:80upx;
	}
	
	.inputs {
	  width: 50%;
	  min-height: 80upx;
	  border-bottom: 1px solid #390;
	  overflow-x: hidden;
	  overflow-y: hidden;
	  word-break: break-all;
	  padding: 0 20upx;
	}
	
	.more {
	  width: 80upx;
	  height: 80upx;
	  position: fixed;
	  top: 80upx;
	  right: 0;
	  background: black;
	  color: white;
	  display: flex;
	  justify-content: center;
	  align-items: center;
	  font-size: 28upx;
	}
	
	.send {
	  width: 100upx;
	  background: #390;
	  height: 80upx;
	  font-size: 28upx;
	  display: flex;
	  justify-content: center;
	  align-items: center;
	  color: white;
	  border-radius: 8upx;
	}
	
	.chat-msg-my {
	  width: 100%;
	  display: flex;
	  margin-top: 20upx;
	  position: relative;
	}
	
	.user-avatar-my {
	  width: 80upx;
	  height: 80upx;
	  border-radius: 10upx;
	  position: absolute;
	  right: 0;
	}
	
	.user-name-my {
	  width: 100%;
	  height: 40upx;
	  font-size: 30upx;
	  color: gray;
	  text-align: right;
	}
	
	.msg-my {
	  width: 75%;
	  margin-left: 11%;
	}
	
	.content-my {
	  min-width: 10%;
	  max-width: 100%;
	  background: rgb(158, 234, 106);
	  border-radius: 10upx;
	  padding: 10upx 20upx 10upx 20upx;
	  font-size: 30upx;
	  word-break: break-all;
	  margin-top: 10upx;
	  min-height: 50upx;
	}
	
	.msg-box-my {
	  width: 100%;
	  display: flex;
	  justify-content: flex-end;
	  position: relative;
	
	}
	.msg-box-my>.menu-list {
	width:160upx;
	position:fixed;
	/* top:10%; */
	/* right:25%; */
	font-size:30upx;
	background:white;
	z-index:52;
	
	  
	
	}
	.msg-box-my>.menu-list>.menu-item{
	  width: 100%;
	  line-height: 60upx;
	  text-align: center;
	  border-bottom:2upx solid #EEE;
	}
	
	.input-box {
	  width: 100%;
	  min-height: 80upx;
	  background: white;
	  display: flex;
	  justify-content: space-around;
	  border-bottom: 1upx solid #bfc0c2;
	  padding: 10upx 0;
	  overflow: hidden;
	}
	
	.bottom-box {
	  width: 100%;
	  position: fixed;
	  bottom: 0;
	  background: rgb(239, 239, 244);
	  /* animation: myfirst 2s;
	    animation-fill-mode: forwards; */
	}
	
	@keyframes myfirst {
	  0% {
	    bottom: -400upx;
	  }
	
	  100% {
	    bottom: 0;
	  }
	}
	
	.else {
	  width: 93%;
	  height: 400upx;
	  margin-left: 3.5%;
	  display: flex;
	  justify-content: space-around;
	  align-items: center;
	  flex-wrap: wrap;
	}
	
	.choose-box {
	  width: 21%;
	  height: 150upx;
	  display: flex;
	  flex-wrap: wrap;
	  justify-content: center;
	  align-items: center;
	}
	
	.container {
	  width: 75%;
	  height: 110upx;
	  display: flex;
	  justify-content: center;
	  align-items: center;
	  background: white;
	  border-radius: 20upx;
	}
	
	.box-img {
	  width: 60upx;
	  height: 60upx;
	}
	
	.txts {
	  text-align: center;
	  color: gray;
	  font-size: 30upx;
	  margin-top: 10upx;
	}
	
	.content-my-img {
	  min-width: 1px;
	  max-width: 100%;
	  border-radius: 8upx;
	  padding: 0;
	  font-size: 30upx;
	  word-break: break-all;
	  margin-top: 10upx;
	  overflow: hidden;
	}
	
	.content-img {
	  min-width: 1px;
	  max-width: 100%;
	  margin-top: 10upx;
	  background: transparent;
	  border-radius: 8upx;
	  padding: 0;
	  overflow: hidden;
	}
	
	.emoji {
	  width: 100%;
	}
	
	.enter {
	  width: 100%;
	  margin-top: 20upx;
	  display: flex;
	  justify-content: center;
	  align-items: center;
	  color: white;
	  height: 45upx;
	  font-size: 30upx;
	  margin-bottom: 20upx;
	}
	
	.enterMsg {
	  background: rgba(15, 0, 0, 0.2);
	  padding-top: 5upx;
	  padding-bottom: 5upx;
	  padding-left: 5upx;
	  padding-right: 5upx;
	  border-radius: 10upx;
	}
	
	.content-my-local {
	  position: relative;
	  min-width: 10%;
	  max-width: 100%;
	  border-radius: 20upx;
	  padding: 10upx 20upx 10upx 20upx;
	  font-size: 30upx;
	  word-break: break-all;
	  margin-top: 10upx;
	}
	
	.speakGif {
	  width: 70%;
	  height: 500upx;
	  position: fixed;
	  top: 30%;
	  margin-left: 15%;
	  z-index: 9;
	}
	
	.voice-shot {
	  width: 150upx;
	  height: 60upx;
	  display: flex;
	  color: gray;
	  align-items: center;
	}
	
	.voice-middle {
	  width: 200upx;
	  height: 60upx;
	  display: flex;
	  color: gray;
	  align-items: center;
	}
	
	.voice-long {
	  width: 230upx;
	  height: 60upx;
	  display: flex;
	  color: gray;
	  align-items: center;
	}
	
	.voice-img {
	  width: 60upx;
	  height: 60upx;
	}
	button{
	  position:relative;
	  display:block;
	  margin-left:0;
	  margin-right:0;
	  padding-left:0;
	  padding-right:0;
	  box-sizing:border-box;
	  font-size:30upx;
	  text-align:center;
	  text-decoration:none;
	  line-height:0;
	  border-radius:10upx;
	  -webkit-tap-highlight-color:transparent;
	  overflow: visible;
	  color:gray;
	  background: rgb(239, 239, 244);
	  border:none;
	}
	button::after{
	  border:none;
	}
	.choose-box-call {
	  width: 21%;
	  height: 150upx;
	  display: flex;
	  flex-wrap: wrap;
	  justify-content: center;
	  align-items: center;
	}
	
	.container-call {
	  width: 75%;
	  height: 110upx;
	  display: flex;
	  justify-content: center;
	  align-items: center;
	  background: white;
	  border-radius: 20upx;
	}
	
	.box-img-call {
	  width: 60upx;
	  height: 60upx;
	}
	.example {
	  display: block;
	  width: 100%;
	  height: 70upx;
	  line-height: 70upx;
	}
	
	.marquee_box {
	  width: 100%;
	  position: relative;
	}
	
	.marquee_text {
	  white-space: nowrap;
	  position: absolute;
	  top: 0;
	  display: flex;
	  flex-direction: row;
	}
	
	.ad-image {
	  width: 40upx;
	  height: 40upx;
	  margin-right: 10upx;
	  margin-top: 15upx;
	}
</style>
